import { defineStore } from 'pinia'
import { ref, reactive } from 'vue'
import api from '../api'
import { cloneDeep } from 'lodash'

// 默认设置
const DEFAULT_SETTINGS = {
  databaseType: 'sqlite',
  databaseConfig: {
    sqlite: {
      storage: './database.sqlite'
    },
    mysql: {
      host: 'localhost',
      port: 3306,
      username: 'root',
      password: '',
      database: 'admin_app'
    },
    sqlserver: {
      server: 'localhost',
      port: 1433,
      user: 'sa',
      password: '',
      database: 'admin_app'
    }
  }
}

export const useSettingsStore = defineStore('settings', () => {
  // 使用默认值初始化设置
  const settings = ref(cloneDeep(DEFAULT_SETTINGS))
  const loading = ref(false)
  const error = ref(null)
  
  // 重置设置为默认值
  function resetSettings() {
    settings.value = cloneDeep(DEFAULT_SETTINGS)
  }
  
  // 合并设置，保留默认值
  function mergeSettings(newSettings) {
    if (!newSettings) return settings.value
    
    return {
      databaseType: newSettings.databaseType || DEFAULT_SETTINGS.databaseType,
      databaseConfig: {
        sqlite: { ...DEFAULT_SETTINGS.databaseConfig.sqlite, ...newSettings.databaseConfig?.sqlite },
        mysql: { ...DEFAULT_SETTINGS.databaseConfig.mysql, ...newSettings.databaseConfig?.mysql },
        sqlserver: { ...DEFAULT_SETTINGS.databaseConfig.sqlserver, ...newSettings.databaseConfig?.sqlserver }
      }
    }
  }
  
  async function loadSettings() {
    loading.value = true
    error.value = null
    
    try {
      const response = await api.getSettings()
      // 合并服务器返回的设置与默认值
      settings.value = mergeSettings(response.data)
    } catch (err) {
      error.value = err.message || '加载设置失败'
      console.error('加载设置失败:', err)
      // 如果加载失败，使用默认设置
      resetSettings()
    } finally {
      loading.value = false
    }
  }
  
  async function saveSettings(newSettings) {
    loading.value = true
    error.value = null
    
    try {
      // 合并新设置与默认值
      const mergedSettings = mergeSettings(newSettings)
      const response = await api.updateSettings(mergedSettings)
      settings.value = mergeSettings(response.data)
      return settings.value
    } catch (err) {
      error.value = err.message || '保存设置失败'
      console.error('保存设置失败:', err)
      throw err
    } finally {
      loading.value = false
    }
  }
  
  async function testConnection(config) {
    loading.value = true
    error.value = null
    
    try {
      // 确保测试的配置包含所有必要的默认值
      const testConfig = mergeSettings(config)
      const response = await api.testConnection(testConfig)
      return response.data
    } catch (err) {
      error.value = err.message || '连接测试失败'
      console.error('连接测试失败:', err)
      throw err
    } finally {
      loading.value = false
    }
  }
  
  return {
    settings,
    loading,
    error,
    loadSettings,
    saveSettings,
    testConnection,
    resetSettings
  }
}) 